<!-- 新闻编辑页面 -->
<template>
  <div>
    <el-card style="width: 70%; margin: 0 auto; margin-top: 20px">
      <h1 style="text-align: center; font-size: 28px">新闻政策管理</h1>
      <div class="title">文章标题</div>
      <el-input placeholder="请输入文章标题" v-model="articleTitle"></el-input>
      <div class="title">新闻政策卡片背景图</div>
      <el-upload
        class="avatar-uploader"
        :show-file-list="false"
        :limit="1"
        ref="upload1"
        :auto-upload="true"
        :http-request="upload"
        :on-exceed="handleExceed"
        v-model:file-list="fileList"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="title">文章内容</div>
      <div style="border: 1px solid #ccc">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          mode="simple"
        />
        <Editor
          style="height: 500px; overflow-y: hidden"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          mode="simple"
          @onCreated="handleCreated"
        />
      </div>
      <el-button @click="save" style="margin: 20px 0; float: right"
        >发布文章</el-button
      >
    </el-card>
  </div>
</template>

<script setup>
import { Plus } from "@element-plus/icons-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { uploadFile, reqAddNew } from "@/api/api";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

const imageUrl = ref("");
const articleTitle = ref("");
const fileList = ref([]);
const upload1 = ref();

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");

// 模拟 ajax 异步获取内容
onMounted(() => {});
const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: "http://127.0.0.1:6888/common/upload",
      fieldName: "file",
      headers: {
        Authorization: sessionStorage.getItem("Token"),
      },
      customInsert: function (response, insertFn) {
        // 将图片插入到编辑器中
        insertFn(response.data);
      },

    },
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
/**发布 */
const save = async () => {
  console.log(valueHtml.value);
  console.log(articleTitle.value);
  console.log(imageUrl.value);
  const res = await reqAddNew({
    title: articleTitle.value,
    content: valueHtml.value,
    cover: imageUrl.value,
  });
  if (res.code == 200) {
    ElMessage.success("发布成功");
    router.push("/news");
  } else {
    ElMessage.error(res.msg);
  }
};

/**上传封面图 */
const upload = async () => {
  console.log(fileList.value[0].raw);

  const res = await uploadFile({ file: fileList.value[0].raw });
  if (res.code == 200) {
    imageUrl.value = res.data;
    // form.avatar = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

/**新添加图片替换上一张 */
const handleExceed = (files) => {
  upload1.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload1.value.handleStart(file);
};
</script>

<style lang="scss" scoped>
.title {
  color: #374151;
  font-weight: bold;
  margin: 10px 0;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
